function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}
// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}
const app = getApp();

module.exports = Behavior({
  data: {
    devices: [],
    connected: false,
    chs: [],
    tojump: false,
    is_reenter: false
  },
  methods: {
    // 重新进入设备控制面板页面
    reenter(str, deviceId, UUID) {
      if (str) {
        this.data.macAddress = str;
      }
      console.log(deviceId, UUID)
      wx.navigateTo({
        url: `/mircoApp/horizon/useDevice/useDevice?mac=${this.data.macAddress}&reenter=1&dId=${deviceId}&sId=${UUID}`,
      })
    },
    openBluetoothAdapter(str) {
      if (str) {
        this.data.macAddress = str;
      }
      wx.openBluetoothAdapter({
        success: (res) => {
          wx.hideLoading();
          console.log('openBluetoothAdapter success', res)
          if (this.data.tojump) {
            wx.navigateTo({
              url: `/mircoApp/horizon/useDevice/useDevice?mac=${this.data.macAddress}`,
            })
            return
          }
          this.startBluetoothDevicesDiscovery()
        },
        fail: (res) => {
          console.log(res)
          if (res.errCode === 10001) {
            wx.hideLoading();
            wx.showModal({
              title: '请开启蓝牙',
            })
            wx.onBluetoothAdapterStateChange(function (res) {
              console.log('onBluetoothAdapterStateChange', res)
              wx.hideLoading();
              if (res.available) {
                if (this.data.tojump) {
                  wx.navigateTo({
                    url: `/mircoApp/horizon/useDevice/useDevice?mac=${this.data.macAddress}`,
                  })
                  return
                }
                this.startBluetoothDevicesDiscovery()
              }
            })
          } else {
            wx.hideLoading();
            wx.showModal({
              title: '提示',
              content: res.errMsg,
            })
          }
        }
      })
    },
    // 安卓手机格式转换的deviceId
    convertToDeviceFormat(deviceId) {
      // 安卓手机格式转换
      var formattedId = deviceId.replace(/:/g, "");
      return formattedId;
    },
    //开始搜寻附近蓝牙信息
    startBluetoothDevicesDiscovery() {
      wx.showLoading({
        title: '连接中',
      })
      console.log(this._discoveryStarted, '_discoveryStarted')
      if (this._discoveryStarted) {
        wx.hideLoading();
        return
      }
      this._discoveryStarted = true
      wx.startBluetoothDevicesDiscovery({
        allowDuplicatesKey: true,
        success: (res) => {
          console.log('startBluetoothDevicesDiscovery success 搜寻附近蓝牙', res)
          this.onBluetoothDeviceFound()
        },
        fail: (err) => {
          wx.hideLoading();
        }
      })
    },
    mac(advertisData) {
      console.log(advertisData, 'mac(advertisData)')
      var buff = advertisData.slice(2, 8);
      var arrayBuff = Array.prototype.map.call(new Uint8Array(buff), x => ('00' + x.toString(16)).slice(-2)).join('');
      var arrayMac = arrayBuff.toUpperCase();
      return arrayMac;
    },
    // 监听搜索到新设备的事件
    onBluetoothDeviceFound() {
      let timer = setTimeout(() => {
        // 停止搜索蓝牙设备的操作
        wx.stopBluetoothDevicesDiscovery({
          success: (res) => {
            console.log('停止搜索蓝牙设备');
            wx.hideLoading();
            // app.tips('抱歉！没有找到相对于的蓝牙设备')
            wx.showToast({
              title: '抱歉！没有找到相对于的蓝牙设备',
              duration: 1500,
              icon: 'none',
              success: () => {
                setTimeout(() => {
                  wx.navigateBack({
                    delta: 1
                  })
                }, 1500);
              }
            })
          },
          fail: (err) => {
            console.error('停止搜索蓝牙设备失败', err);
          }
        });
      }, 5000);
      wx.onBluetoothDeviceFound((res) => {
        res.devices.forEach(device => {
          if (!device.name && !device.localName) {
            return
          }
          let oris = wx.getSystemInfoSync().platform;
          if (device.name == 'HUIYANXINGDONG') {
            if (oris == 'ios') {
              console.log(this.data.macAddress, this.mac(device.advertisData), device, ab2hex(device.advertisData), 'HUIYANXINGDONGHUIYANXINGDONG')
              if (this.data.macAddress == this.mac(device.advertisData)) {
                this.createBLEConnection(device.deviceId);
                clearTimeout(timer); // 找到对应的macAddress，清除定时器
                return
              }
            } else {
              if (this.data.macAddress == this.convertToDeviceFormat(device.deviceId)) {
                this.createBLEConnection(device.deviceId);
                clearTimeout(timer); // 找到对应的macAddress，清除定时器
                return
              }
            }
          }
        })
      })
    },
    createBLEConnection(deviceId, dsName) {
      wx.createBLEConnection({
        deviceId,
        success: (res) => {
          console.log(res)
          wx.hideLoading();
          this.setData({
            connected: true,
            name: dsName,
            deviceId: deviceId,
          })
          this.getBLEDeviceServices(deviceId)
          this.onBLEConnectionStateChange();
        },
        fail: (err) => {
          console.log(err)
          wx.hideLoading();
          wx.navigateBack({
            delta: 1
          })
        }
      })
      this.stopBluetoothDevicesDiscovery()
    },
    onBLEConnectionStateChange() {
      wx.onBLEConnectionStateChange((res) => {
        console.log('wx.onBLEConnectionStateChange()设备状态 ', res)
        // 该方法回调中可以用于处理连接意外断开等异常情况
        if (!res.connected) {
          wx.showToast({
            title: '连接已断开',
            icon: 'none'
          })
          this.setData({
            runing: false,
            connected: false
          })
        } else {
          this.setData({
            connected: true
          })
        }
      })
    },
    // 获取蓝牙服务
    getBLEDeviceServices(deviceId) {
      wx.getBLEDeviceServices({
        deviceId,
        success: (res) => {
          for (let i = 0; i < res.services.length; i++) {
            if (res.services[i].isPrimary) {
              this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
              // console.log('222222221111111111', res.services[i])
              // this.getBluetoothDevices(deviceId)
              return
            }
          }
        }
      })
    },
    // 获取蓝牙服务特征
    getBLEDeviceCharacteristics(deviceId, serviceId, key = '') {
      console.log(deviceId, serviceId, key, '获取蓝牙服务特征')
      let that = this;
      wx.getBLEDeviceCharacteristics({
        deviceId,
        serviceId,
        success: (res) => {
          for (let i = 0; i < res.characteristics.length; i++) {
            let item = res.characteristics[i]
            if (item.properties.write) {
              this.setData({
                canWrite: true
              })
              this._deviceId = deviceId
              this._serviceId = serviceId
              this._characteristicId = item.uuid
              console.log('_characteristicId写数据的uuid', item.uuid)
              // 直接发送验证地址的指令
              this.verify();
              if (key == 'checkStatus') {
                // 重新进入设备面板先获取一下设备状态
                this.checkStatus();
              }
            }
            if (item.properties.notify || item.properties.indicate) {
              wx.notifyBLECharacteristicValueChange({
                deviceId,
                serviceId,
                characteristicId: item.uuid,
                state: true,
                type: 'notification',
                success(res) {
                  console.log("notifyBLECharacteristicValueChange开启了", res)
                }
              })
            }
            wx.onBLECharacteristicValueChange((res) => {
              console.log(res.value)
              let str = ab2hex(res.value);
              if (str.includes(this.test1('41444F4B'))) {
                console.log('地址验证成功', str)
              } else if (str.includes(this.test1(`544953${this.string2Hex(Number(this.data.time))}`))) {
                console.log('发送定时回调', str, this.test1(`544953${this.string2Hex(Number(this.data.time))}`))
              } else if (str.includes(this.test1('4D730000'))) {
                // console.log('设置S模式', str)
              } else if (str.includes(this.test1('4D610000'))) {
                // console.log('设置A模式', str)
              } else if (str.includes(this.test1('4D690000'))) {
                // console.log('设置I模式', str)
              } else if (str.includes(this.test1('53544152'))) {
                console.log('开始运行', str, this.test1('53544152'))
                if (this.data.setting.has_one_machine_type.min_modal > 1) {
                  console.log(this.data.setting.has_one_machine_type.min_modal, '开启了最小强度')
                  this.sendOpenOption(`4C4556${this.string2Hex(Number(this.data.setting.has_one_machine_type.min_modal))}`);
                }
                this.setData({
                  runing: true,
                  strength: this.data.setting.has_one_machine_type.min_modal
                })
              } else if (str.includes(this.test1('4c4556'))) {
                // console.log('增加一个档位', str, this.test1('4c45'))
              } else if (str.includes(this.test1('4c4556'))) {
                // console.log('减少一个档位', str, this.test1('4c45'))
              } else if (str.includes(this.test1('5353'))) {
                let ind = str.indexOf(this.test1('5353'));
                let nstr = str.slice(ind + this.test1('5353').length, str.length);
                let str1 = this.hexToDecimal(nstr);
                let lastTwoChars = str1.substr(-2);
                let hexValue = parseInt(lastTwoChars, 16);
                let lever = this.convertUnicodeToString(nstr).slice(this.convertUnicodeToString(nstr).length - 4, this.convertUnicodeToString(nstr).length - 2);
                if (hexValue >= 1) {
                  this.setData({
                    runing: true
                  })
                }
                this.setData({
                  strength: hexValue
                })
                if (this.data.reenter) {
                  // 如果是已连接的进来获取一下模式赋值到页面
                  console.log("如果是已连接的进来获取一下模式赋值到页面", lever)
                  if (lever == "73") {
                    this.setData({
                      modelKey: "s"
                    })
                  } else if (lever == "61") {
                    this.setData({
                      modelKey: "a"
                    })
                  } else if (lever == "69") {
                    this.setData({
                      modelKey: "i"
                    })
                  }
                }
                console.log(this.convertUnicodeToString(nstr), "查询状态", lever)
              } else if (str == '303030303030303018914e') {
                console.log(this.data.macAddress, '停止设备返回二维码页面this.data.macAddress', str, that.data.deviceId)
                wx.hideLoading();
                wx.closeBLEConnection({
                  deviceId: that.data.deviceId,
                  success: (res) => {
                    console.log('断开连接成功', that.data.deviceId);
                    wx.showToast({
                      title: '设备停止成功',
                      duration: 1500,
                      icon: 'none',
                      success: async () => {
                        that.setData({
                          runing: false,
                          connected: false,
                          strength: this.data.setting.has_one_machine_type.min_modal,
                          modelKey: '',
                          time: ''
                        })
                        that._discoveryStarted = false;
                        await that.serveEnd();
                        wx.navigateBack({
                          delta: 1
                        })
                      }
                    })
                  }
                })
              } else {
                console.log('wwwwwwwwwwwwwww', str, this.test1(str))
                // console.log('riiiiiiiiiii:::::::dd',this.test1(str))
              }
            })
          }
        },
        fail(err) {
          console.log('getBLEDeviceCharacteristics', err.errCode)
          if (err.errCode == 10006) {
            wx.showModal({
              title: '提示',
              content: '当前连接已断开',
              complete: (res) => {
                if (res.cancel) {
                  wx.navigateBack({
                    delta: 1,
                  })
                }
                if (res.confirm) {
                  wx.navigateBack({
                    delta: 1,
                  })
                }
              }
            })
            app.tips('当前连接已断开')
            return
          }
        }
      })
    },
    convertUnicodeToString(unicodeArray) {
      let str = '';
      for (let i = 0; i < unicodeArray.length; i += 2) {
        const unicode = parseInt(unicodeArray.substr(i, 2), 16);
        str += String.fromCharCode(unicode);
      }
      return str;
    },
    hexToDecimal(hexString) {
      var decimalString = "";
      for (var i = 0; i < hexString.length; i += 2) {
        var hex = hexString.substr(i, 2);
        var decimal = parseInt(hex, 16);
        decimalString += String.fromCharCode(decimal);
      }
      return decimalString;
    },
    test1(str) {
      let unicodeArray = '';
      for (let i = 0; i < str.length; i++) {
        const unicode = str.charCodeAt(i).toString(16).padStart(2, '0');
        unicodeArray += (`${unicode}`);
      }
      return unicodeArray;
    },
    test(str) {
      let unicodeArray = [];
      for (let i = 0; i < str.length; i++) {
        const unicode = str.charCodeAt(i).toString(16).padStart(2, '0');
        unicodeArray.push(`0x${unicode}`);
      }
      return unicodeArray;
    },
    stringToUnicode(str, child, unShift) {
      let unicodeArray = [];
      for (let i = 0; i < str.length; i++) {
        const unicode = str.charCodeAt(i).toString(16).padStart(2, '0');
        unicodeArray.push(`0x${unicode}`);
      }
      if (child) {
        unicodeArray.push('0x18', '0x00');
      }
      if (unShift) {
        let noCode = ['0xFE', '0x01', '0x00', '0x16', '0x75', '0x31', '0x00', '0x00', '0x0A', '0x00', '0x12', '0x08']
        unicodeArray = [...noCode, ...unicodeArray]
      } else {
        let noCode = ["0xFE", "0x01", "0x00", "0x1e", "0x75", "0x31", "0x00", "0x00", "0x0A", "0x00", "0x12", "0x10"]
        unicodeArray = [...noCode, ...unicodeArray]
      }
      return unicodeArray;
    },
    // 指令封装
    sendOpenOption(str, key = true) {
      let arr = this.stringToUnicode(str, true, key)
      if (arr.length > 20) {
        this.writeBLECharacteristicValue(arr.slice(0, 20))
        this.writeBLECharacteristicValue(arr.slice(20))
      } else {
        this.writeBLECharacteristicValue(arr)
      }
    },
    // 发送封装
    writeBLECharacteristicValue(arr) {
      let buffer = new ArrayBuffer(arr.length)
      let dataView = new DataView(buffer)
      for (let i = 0; i < arr.length; i++) {
        dataView.setUint8(i, arr[i]);
      }
      console.log(this._deviceId, this._serviceId, this._characteristicId)
      wx.writeBLECharacteristicValue({
        deviceId: this._deviceId,
        serviceId: this._serviceId,
        characteristicId: this._characteristicId,
        value: buffer,
        success: function (res) {
          console.log("指令发送成功", buffer);
        },
        fail: function (res) {
          console.log("指令发送失败", buffer);
        }
      });
    },
    // 验证地址
    verify() {
      this.sendOpenOption(`4144${this.data.macAddress}`, false);
      this.setData({
        strength: this.data.setting.has_one_machine_type.min_modal
      })
    },
    // 停止新设备搜索
    stopBluetoothDevicesDiscovery() {
      wx.stopBluetoothDevicesDiscovery()
    },
    // 关闭蓝牙
    closeBluetoothAdapter() {
      wx.closeBluetoothAdapter()
      this._discoveryStarted = false
    },
    sendOpen5() {
      this.sendOpenOption('53544f50')
    },
    // 查询状态
    checkStatus() {
      this.sendOpenOption('53544154')
      console.log('查询状态指令发送')
    }
  }
})